package com.example.demo.controller;


import com.example.demo.util.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

//文件上传下载
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${furniture.path}")
    String path;
    //文件上传,从其他地方上传到文件保存的地方
    @PostMapping("/upload")
    public JsonResult<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        System.out.println("123"+originalFilename);
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println("12"+substring);
        //防止重复名字
        String s = UUID.randomUUID().toString()+substring;
        System.out.println("1"+s);
        //创建一个目录对象
        File dir=new File(path);
        //是否存在该目录
        if (!dir.exists()){
            //创建文件夹
            dir.mkdirs();
        }
        try {
            //上传文件
            file.transferTo(new File(path+s));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JsonResult<>(200, s);
    }
    //从文件保存的地方将图片传输到前端
//    @GetMapping("/download")
//    public void download(String name, HttpServletResponse response){
//        try {
//            byte[] bytes=new byte[1024];
//            FileInputStream fileInputStream=new FileInputStream(path+name);
//            ServletOutputStream outputStream = response.getOutputStream();
//            int read ;
//            while ( (read= fileInputStream.read(bytes))!=-1){
//                outputStream.write(bytes,0,read);
//                outputStream.flush();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
